package cn.tedu;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Demo10 {
    public static void main(String[] args) {
        Scanner sca = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = sca.nextLine();
        System.out.println("请输入密码:");
        String password = sca.nextLine();
        //获取连接 判断用户输入的信息是否正确
        try (Connection conn = DBUtils.getConn();){
            /*Statement s = conn.createStatement();*/
            /*ResultSet rs = s.executeQuery("select username,password from user");
            while(rs.next()){
                String username = rs.getString(1);
                String password = rs.getString(2);
                System.out.println("查询成功！");
                System.out.println(username+","+password);
                if(usename1.equals(username) && password1.equals(password)){
                    System.out.println("恭喜你,登录成功！");
                }else{
                    System.out.println("用户名或密码错误！");
                }
            }*/
            /*ResultSet rs = s.executeQuery("select count(*) from user where " +
                    "username='"+username+"' and password='"+password+"'");*/
            /*String sql = "select count(*) from user where username='"+username+"' and password='"+password+"'" +
                    "");*/
            //通过preparedStatememt解决SQL注入问题
            String sql = "select count(*) from user where username=? and password=?";
            //编译SQL语句的时间点从之前执行时,提前到了创建对象时,好处是此时编译用户输入的内容,还不在SQL语句里面
            //只是将原有SQL语句进行编译,此时可以将原有的SQL语句的逻辑部分锁死
            PreparedStatement ps = conn.prepareStatement(sql);
            //把?替换成变量1和2代表的是？的位置    此时替换时只能以值的形式添加到原有的SQL语句中,因为逻辑部分已经
            //编译好  已经锁死,这样用户输入的内容则不会影响原有SQL语句的逻辑
            ps.setString(1,username);
            ps.setString(2,password);
            ResultSet rs = ps.executeQuery();
            //游标往下移动,指向查询回来的数据
            rs.next();
            //从结果集对象中获取此时游标指向的数据  获取count的值,>0表示存在用户    <0表示没有该用户
            int count = rs.getInt(1);
            if(count>0){
                System.out.println("登录成功！");
            }else{
                System.out.println("用户名或密码错误！");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }
}
